<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h1>部门列表</h1>
        </div>
      </template>
      <!-- 搜索 -->
      <div class="search">
        <el-form :inline="true" :model="searchBox">
          <el-form-item label="名称">
            <el-input v-model="searchBox.name"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="searchFN" color="#06988B">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 功能按钮 -->
      <div class="fnBtn">
        <el-button class="addbtn" type="primary" @click="openAddDepartment">
          添加部门</el-button>
          <el-button class="addbtn" type="warning" @click="batchDelete">
            批量删除</el-button> 
      </div>
      <!-- 表格 -->
      <el-table :data="departmentList" v-loading="loading" style="width: 100%" :show-overflow-tooltip="true" stripe border @selection-change="handleSelectionChange">
        <el-table-column type="selection"  width="55" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="number" label="人数" />
        <el-table-column prop="leader" label="负责人" />
        <el-table-column prop="establishTime" label="成立时间" >
          <template #default="scope">
            {{ FormatDate(scope.row.establishTime,'yyyy-MM-dd') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <el-button class="editbtn" @click="handleEdit(scope.row)"  type="primary">
              <Edit class="el-size" />修改
            </el-button>
            <el-button class="editbtn" type="warning" @click="handleDelete(scope.row)" 
              >
              <Delete class="el-size" />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination" v-model:current-page="Page" v-model:page-size="Limit"
        :page-sizes="[1, 10, 20, 30]" :small="small" :disabled="disabled" :background="false"
        layout="total, prev, pager, next, sizes, jumper" :total="Number(total)" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-card>
    <!-- 添加部门弹窗 -->
    <!-- 弹框 -->
    <el-dialog v-model="dialogVisible" :title="dtitle" width="600px" :before-close="handleClose"
      :close-on-click-modal="false">
      <!-- 表单 -->
      <el-form :model="addForm" ref="addFormRef" :rules="addRules" label-position="top" label-width="100px">
        <!-- 弹窗 -->
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="人数" >
          <el-input v-model="addForm.number"></el-input>
        </el-form-item>
        <el-form-item label="负责人" >
          <el-input v-model="addForm.leader"></el-input>
        </el-form-item>
        <el-form-item label="成立时间" >
          <!-- <el-input v-model="addForm.establishTime"></el-input> -->
          <el-date-picker v-model="addForm.establishTime" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
       
        
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="addDepartment">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getDepartmentListAPI, addDepartmentAPI, editDepartmentAPI, delDepartmentAPI, delDepartmentsAPI } from '../api/department';
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { FormatDate } from '../utils/util';

const searchBox = ref({
  name: '',
});

const searchFN = () => {
  getDepartmentList();
};


//控制loading状态
const loading = ref(true);

//分页
const total = ref(0);
const small = ref(false);
const disabled = ref(false);
const Page = ref(1);
const Limit = ref(10);
const multipleSelection = ref([]); // 表格选中的数据

// 添加Department表单
const addForm: any = ref({});

//获取表单的请求数据
const departmentList = ref([]); // 表格数据
const dialogVisible = ref(false); // 控制弹窗开关
const addFormRef: any = ref(null); // 声明一个 ref 用于引用表单组件
const dtitle = ref('添加部门');

onMounted(() => {
  getDepartmentList();
});
// 添加Department表单校验
const addRules = ref({
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
});
// 获取部门列表
const getDepartmentList = async () => {
  const res: any = await getDepartmentListAPI({
    Name: searchBox.value.name,
    Page: Page.value,
    Limit: Limit.value,
  });
  departmentList.value = res.data;
  total.value = res.count;
  loading.value = false;
};
// 打开添加部门弹窗
const openAddDepartment = (event: any) => {
  // 重置按钮样式
  dtitle.value = '添加部门';
  dialogVisible.value = true;
};
// 修改表格数据
const handleEdit = (row: any) => {
  // 开启弹窗
  dtitle.value = '修改部门信息';
  dialogVisible.value = true;
  addForm.value = JSON.parse(JSON.stringify(row));
};
// 删除表格数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm('是否删除此部门?')
    .then(async () => {
      //调用删除接口
      await delDepartmentAPI(row._id);
      ElMessage.success('删除成功');
      //删除完调用获取部门列表接口重新渲染
      getDepartmentList();
    })
    .catch(() => {
      // catch error
      ElMessage.warning('您已取消删除');
    });
};

// 添加部门
const addDepartment = async () => {
  try {
    console.log(addForm.value);
    // 执行表单校验
    await addFormRef.value.validate();
    // 校验成功后发起添加请求
    if (!addForm.value._id) {
      await addDepartmentAPI(addForm.value);
      ElMessage.success('添加成功');
    } else {
      await editDepartmentAPI(addForm.value);
      ElMessage.success('修改成功');
    }
    // 关闭并重置弹窗
    handleClose();
    // 成功后通知父组件刷新表格
    getDepartmentList();
  } catch (error) {
    ElMessage.error('表单校验失败,请检查输入');
    console.log(error);
  }
};
// 关闭添加部门弹窗
const handleClose = () => {
  dialogVisible.value = false;
  // 关闭清空表单
  addFormRef.value.resetFields();
  addForm.value = {};
};
// 分页
const handleSizeChange = (val: any) => {
  Limit.value = val;
  getDepartmentList();
};
//处理切换页码
const handleCurrentChange = (val: any) => {
  Page.value = val;
  getDepartmentList();
};
// 处理表格选择
const handleSelectionChange = (val:any)=> {
  multipleSelection.value = val;
}
// 批量删除
const batchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的部门');
    return;
  }  
  const ids = multipleSelection.value.map((item: any) => item._id);
  ElMessageBox.confirm('是否删除选中的部门?')
    .then(async () => {
      //调用删除接口
      await delDepartmentsAPI({ids});
      ElMessage.success('删除成功');
      //删除完调用获取部门列表接口重新渲染
      getDepartmentList();
    })
}
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

:deep(.search .search-form) {
  display: flex;
}

.pagination {
  margin-top: 20px;
}

.addbtn {
  margin-bottom: 20px;
}

::v-deep(.is-active) {
  background-color: #06988b;
  color: #fff;
}

::v-deep(.el-pager li.is-active) {
  // background-color: #06988b;
  color: #fff;
}
</style>
